package com.xsjiong.jaript;

import com.xsjiong.jaript.lexer.JLexer;
import com.xsjiong.jaript.lexer.JSymbols;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import com.xsjiong.jaript.utils.*;

public class Main {
	public static void main(String[] args) throws Throwable {
		StartTask();
		Class c = null;
		for (int i=0;i<10000000;i++)
			c = JReflector.getClassSafely("java.lang.Class");
		EndTask("GetClass");
	}

	private static void CompilerTest() throws Throwable {
		try {
			JContext cx = new JContext();
			JCompiler compiler = cx.getCompiler();
			StartTask();
			byte[] data = compiler.compileCode("import java.lang.System;\nSystem.out.println(2+6);");
			EndTask("Expression");
			System.out.println(Arrays.toString(data));
			cx.getRunner().run(data, compiler.getStringPool());
			//System.out.println(Arrays.toString(code));
			//cx.getRunner().run(code, compiler.getStringPool());
		} catch (JCompilerException e) {
			e.printStackTrace();
		}
	}

	private static void OperatorTest() {
		Object a = new Integer(19260817);
		Object b = new Integer(2);
		StartTask();
		JOperator op = JOperator.getOperator(a);
		for (int i = 0; i < 1000000; i++)
			op.calc(a, b, JSymbols.Division);
		EndTask("OP");
		int res;
		StartTask();
		for (int i = 0; i < 1000000; i++)
			res = (Integer) a / (Integer) b;
		EndTask("Normal");
	}

	private static void ImportHelperTest() throws Throwable {
		JImportHelper helper = new JImportHelper();
		helper.importPackage("com.xsjiong.jaript");
		System.out.println(helper.getClassBySimpleName("JContext"));
	}

	private static void LexerTest() {
		try {
			System.out.println("Start Lexer...");
			JLexer lexer = new JLexer("import java.lang/*d*/.*;\nimport java.util..HashMap;");
			//JLexer lexer = new JLexer("public class Main {\n    public static void main(String[] args) {\n      System.out.println(\"Hello, World!\");\n        System.out.println(1 >>> 5);\n  }\n}");
			byte Symbol;
			while (!lexer.isEOF()) {
				Symbol = lexer.ReadSymbol();
				System.out.println("<" + JSymbols._GetSymbolName(Symbol) + "> " + (Symbol == JSymbols.String ? lexer.getString() : lexer.getToken()));
			}
			System.out.println("End Lexer.");
		} catch (Throwable t) {
			t.printStackTrace();
		}
	}

	private static long StartTime;

	private static final void StartTask() {
		StartTime = System.nanoTime();
	}

	private static final void EndTask(String name) {
		StartTime = System.nanoTime() - StartTime;
		System.out.println(name + "耗时: " + TimeUnit.NANOSECONDS.toMillis(StartTime));
	}
}
